from google.appengine.ext import db

import gaev
from gaev import utils
from gaev.utils import session
from gaev.actions import *


class AddToCartAction(NonvisualAction):
	image_url='/static/images/icon_cart.gif'
	def perform_nonvisual(self):
		entity=self.object
		key=str(entity.key())
		keys=get_cart_keys()
		if key not in keys:
			keys.append(key)
			set_cart_keys(keys)

class RemoveFromCartAction(NonvisualAction):
	def perform_nonvisual(self):
		entity=self.object
		key=str(entity.key())
		keys=get_cart_keys()
		if key in keys:
			keys.remove(key)
		set_cart_keys(keys)
		
class EmptyCartAction(NonvisualAction):
	def perform_nonvisual(self):
		ssn=session.Session()
		set_cart_keys([])

def get_cart_actions(object):
	return ['empty_cart']
def get_cart_action(object, name):
	if name=='empty_cart':
		return EmptyCartAction(None)
register_action_getter(None, get_cart_action, get_cart_actions)

def get_entity_cart_actions(entity):
	return ['add_to_cart']

def get_entity_cart_action(entity, name):
	if name=='add_to_cart':
		return AddToCartAction(entity)
	elif name=='remove_from_cart':
		return RemoveFromCartAction(entity)
	

def register_model(model):
	register_action_getter(model, get_entity_cart_action, get_entity_cart_actions, True)

def get_cart_spec():
	if 'cart_items' in ssn:
		return ssn['cart_items']
	else:
		import pickle
		import base64
		return base64.b64encode(pickle.dumps([]))
def decode_cart_spec(str):
	item_keys=pickle.loads(base64.b64decode(itstr))
	items=gaev.BaseModel.get(item_keys);
	return items
	
def get_cart_keys():
	import pickle, base64
	ssn=session.Session()
	if 'cart_items' in ssn:
		itstr=ssn['cart_items']
		item_keys=pickle.loads(base64.b64decode(itstr))
		return item_keys
	else:
		return []
def set_cart_keys(keys):
	import pickle, base64
	itstr=base64.b64encode(pickle.dumps(keys))
	ssn=session.Session()
	ssn['cart_items']=itstr

def get_cart_items():
	item_keys=get_cart_keys()
	if len(item_keys)==0:
		return []
	items=gaev.BaseModel.get(item_keys);
	return items
def set_cart_items(items):
	keys=[str(item.key()) for item in items]
	set_cart_keys(keys)
	
def cart_processor(request):
	res={}
	res['cart_items']=get_cart_items()
	return res
